<template>
  <div class="change-add-edit">
    <Button type="primary" @click="handleClick">{{ text }}</Button>
    <el-dialog :visible.sync="visible" append-to-body :title="isEdit?'变更':'新增'" @open="handleOpen" @close="handleColse">
      <FormContainer :column="2">
        <el-form ref="form" :model="formData" :rules="formRules" label-width="80px">
          <el-form-item label="业务组" prop="handlerGroupNo">
            <el-select v-model="formData.handlerGroupNo" :disabled="!!formData.handlerPostCode" placeholder="请选择业务组" clearable filterable @change="handleChange">
              <el-option v-for="b in businessList" :key="b.groupNo" :value="b.groupNo" :label="b.groupName"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="handlerPostCode" label="岗位">
            <SelectForDict :disabled="!!formData.handlerGroupNo" :code.sync="formData.handlerPostCode" :name.sync="formData.handlerPostName" dict-type-code="DEPT_POST_CODE" placeholder="请选择岗位" clearable filterable @on-change="handlePostChange"></SelectForDict>
          </el-form-item>
          <el-form-item v-if="formData.handlerGroupNo || formData.handlerPostCode" label="坐席" prop="handler">
            <el-select
              v-if="formData.handlerGroupNo"
              v-model="formData.handler"
              :disabled="!formData.handlerGroupNo"
              placeholder="请选择坐席"
              remote
              :remote-method="getBusinessMembers"
              clearable
              filterable
              style="width:100% !important"
              @change="getStaffName"
            >
              <el-option v-for="h in handlerList" :key="h.accountNo" :value="h.accountNo" :label="`${h.staffName}(${h.accountNo})`"></el-option>
            </el-select>
            <SearchSelectPicker
              v-if="formData.handlerPostCode"
              url="/call-center/api/v1/workOrderEcosReceiver/queryPostHandler/page"
              placeholder="请选择"
              lable-name="receiverName"
              value-name="receiver"
              :must-pid="true"
              :parent-id="formData.handlerPostCode"
              :disabled="!formData.handlerPostCode"
              :params="{query:{postCode:formData.handlerPostCode},type:0}"
              :value.sync="formData.handler"
              :lable.sync="formData.handlerName"
              @selectChange="handleEcosReceiver"
            ></SearchSelectPicker>
          </el-form-item>
          <el-form-item :span="24">
            <div style="text-align: right;">
              <Button type="primary" @click="handelCancel">取消</Button>
              <Button type="primary" :disabled="!formData.handler" @click="handleClickConfirm">确定</Button>
            </div>
          </el-form-item>
        </el-form>
      </FormContainer>
    </el-dialog>
  </div>
</template>
<script>
import FormContainer from '@/components/FormContainer'
import SelectForDict from '@/components/SelectForDict'
import SearchSelectPicker from '@/components/SearchSelectPicker'
import { getBusinessAll, getBusinessMembers } from '@/api/business'
import { filtersRaw, pageRequsetBody } from '@/utils'
import { changeHandlerAdd, changeHandlerEdit } from '@/api/workOrder'
export default {
  name: 'AddEdit',
  components: {
    FormContainer,
    SelectForDict,
    SearchSelectPicker
  },
  props: {
    row: {
      type: Object,
      default: undefined
    },
    text: {
      type: String,
      default: '新增'
    },
    isEdit: {
      type: Boolean,
      default: false
    },
    workOrderIds: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      visible: false,
      formData: {
        groupId: '',
        handler: '', //	处理人账号
        handlerGroupName: '', //	业务组名称
        handlerGroupNo: '', //	业务组编码
        handlerName: '', //	处理人姓名
        handlerPhone: '', //	处理人电话
        handlerPostCode: '', //	岗位编码
        handlerPostName: '', //	岗位名称
        qupOrganization: '', //	QUP组织
        qupOrganizationName: '' //	QUP组织名称
      },
      formRules: {
        // groupId: [{ required: true, message: '请选择业务组', trigger: 'change' }],
        // handlerPostCode: [{ required: true, message: '请选择岗位', trigger: 'change' }],
        handler: [{ required: true, message: '请选择坐席', trigger: 'change' }]
      },
      // 只能选择以下业务组
      groupNoList: ['35', '34', '33', '32', '26', '20', '22', '23', '24', '38', '39'],
      businessList: [],
      handlerList: []
    }
  },
  computed: {
  },
  created() {
    if (this.businessList.length === 0) {
      this.getBusinessAll()
    }
  },
  methods: {
    handleClick() {
      if (this.isEdit) {
        if (this.row && Object.keys(this.row).length > 0) {
          this.visible = true
        } else {
          this.$message.warning('请选择【变更】项')
        }
        return
      }
      this.visible = true
    },
    handleOpen() {
      // if (this.isEdit) {
      //   this.initFormData()
      // }
    },
    handleColse() {
      this.clearFormData()
    },
    initFormData() {
      Object.keys(this.formData).forEach(k => {
        const v = this.row[k]
        const isNone = v === undefined || v === null
        this.$set(this.formData, k, isNone ? '' : v)
      })
    },
    clearFormData() {
      Object.keys(this.formData).forEach(k => {
        this.$set(this.formData, k, '')
      })
    },
    // 获取所有业务组
    getBusinessAll() {
      getBusinessAll().then(res => {
        this.businessList = res.data.filter(e => {
          return this.groupNoList.includes(e.groupNo)
        })
      })
    },
    handleChange(groupNo) {
      this.$set(this.formData, 'handler', '')
      this.$set(this.formData, 'handlerName', '')
      this.$set(this.formData, 'handlerPhone', '')
      this.$set(this.formData, 'qupOrganization', '')
      this.$set(this.formData, 'qupOrganizationName', '')
      this.$set(this.formData, 'handlerPostCode', '')
      this.$set(this.formData, 'handlerPostName', '')

      if (!groupNo) {
        this.$set(this.formData, 'handlerGroupNo', '')
        this.$set(this.formData, 'handlerGroupName', '')
      }
      for (const item of this.businessList) {
        if (item.groupNo === groupNo) {
          this.$set(this.formData, 'handlerGroupName', item.groupName)
          this.$set(this.formData, 'groupId', item.id)
          break
        }
      }
      this.getBusinessMembers('')
    },
    // 获取坐席
    getBusinessMembers(v) {
      if (!this.formData.groupId) {
        this.handlerList = []
        return
      }
      const data = {
        pageFlag: true,
        filtersRaw: []
      }
      if (/^[a-zA-Z]+$/.test(v)) {
        data.filtersRaw.push(filtersRaw('accountNo', v, 'like'))
      } else {
        data.filtersRaw.push(filtersRaw('staffName', v, 'like'))
      }
      getBusinessMembers(pageRequsetBody(data), this.formData.groupId).then(res => {
        this.handlerList = res.data.records
      })
    },
    handlePostChange() {
      this.$set(this.formData, 'groupId', '')
      this.$set(this.formData, 'handlerGroupName', '')
      this.$set(this.formData, 'handlerGroupNo', '')
      this.$set(this.formData, 'handler', '')
      this.$set(this.formData, 'handlerName', '')
      this.$set(this.formData, 'handlerPhone', '')
      this.$set(this.formData, 'qupOrganization', '')
      this.$set(this.formData, 'qupOrganizationName', '')
    },
    // 获取坐席姓名
    getStaffName(v) {
      if (!v) {
        this.$set(this.formData, 'handler', '')
        this.$set(this.formData, 'handlerName', '')
        this.$set(this.formData, 'handlerPhone', '')
        this.$set(this.formData, 'qupOrganization', '')
        this.$set(this.formData, 'qupOrganizationName', '')
        return
      }
      for (const item of this.handlerList) {
        if (item.accountNo === v) {
          this.$set(this.formData, 'handlerName', item.staffName)
          this.$set(this.formData, 'handlerPhone', '')
          this.$set(this.formData, 'qupOrganization', '')
          this.$set(this.formData, 'qupOrganizationName', item.organization)
        }
      }
    },
    handleEcosReceiver(v) {
      if (!v) {
        this.$set(this.formData, 'handler', '')
        this.$set(this.formData, 'handlerName', '')
        this.$set(this.formData, 'handlerPhone', '')
        this.$set(this.formData, 'qupOrganization', '')
        this.$set(this.formData, 'qupOrganizationName', '')
        return
      }
      this.$set(this.formData, 'handlerPhone', v.receiverPhone)
      this.$set(this.formData, 'qupOrganization', '')
      this.$set(this.formData, 'qupOrganizationName', '')
    },
    handelCancel() {
      this.visible = false
    },
    handleClickConfirm() {
      return this.$refs.form.validate().then(() => {
        const http = !this.isEdit ? changeHandlerAdd : changeHandlerEdit
        const data = {
          newHandler: this.formData,
          workOrderIds: this.workOrderIds
        }
        if (this.isEdit) {
          data.oldHandler = this.row.handler
        }
        return http(data).then(res => {
          this.$message.success('操作成功!')
          this.visible = false
          this.$emit('refresh')
        })
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.change-add-edit{
  display: inline-block;
  text-align: initial;
}
</style>
